<!doctype html>
<html>
<title>Echo referrer in ServiceWorker: from a document with the default referrer policy</title>
<script src = "/resources/get-host-info.js?pipe=sub"></script>
<script src = "/resources/testharness.js"></script>
<script src = "/resources/testharnessreport.js"></script>
<script src = "/serviceworker/resources/test-helpers.js"></script>
<script src = "/fetch/resources/fetch-test-helpers.js"></script>
<script src = "/fetch/resources/fetch-test-options.js"></script>
<script>
const SCRIPT = '/fetch/referrer/resources/echo-referrer.js';
const SCOPE = '/fetch/referrer/resources/empty.html';
const {BASE_ORIGIN} = get_fetch_test_options();
const URL = BASE_ORIGIN + '/fetch/resources/echo';
const REFERRER_SOURCE = BASE_ORIGIN + SCOPE;

const TESTS = [
  [URL, 'about:client',
    '', REFERRER_SOURCE, 'strict-origin-when-cross-origin'],
  [URL, 'about:client', 'no-referrer',
    '', 'no-referrer'],
  [URL, 'about:client', 'no-referrer-when-downgrade',
    REFERRER_SOURCE, 'no-referrer-when-downgrade'],
  [URL, 'about:client', 'origin',
    BASE_ORIGIN + '/', 'origin'],
  [URL, 'about:client', 'origin-when-cross-origin',
    REFERRER_SOURCE, 'origin-when-cross-origin'],
  [URL, 'about:client', 'unsafe-url',
    REFERRER_SOURCE, 'unsafe-url'],
];

promise_test(t => {
    return service_worker_unregister_and_register(t, SCRIPT, SCOPE).then(r => {
        add_completion_callback(() => r.unregister());
        return wait_for_state(t, r.installing, 'activated');
    }).then(() => {
        return with_iframe(SCOPE);
    }).then(frame => {
        add_completion_callback(() => frame.remove());
        for (const [url, referrer, referrer_policy, expected_referrer,
                    expected_referrer_policy] of TESTS) {
          promise_test(t => {
              // Use |frame.contentWindow.fetch| so that the fetch request
              // is intercepted by the service worker.
              return frame.contentWindow.fetch(url,
                  {referrer: referrer, referrerPolicy: referrer_policy})
                .then(res => res.text())
                .then(text => {
                    assert_equals(text, JSON.stringify({
                      referrer: expected_referrer,
                      referrerPolicy: expected_referrer_policy,
                    }));
                  });
            }, `url = ${url}, referrer = ${referrer}, policy = ${referrer_policy}`);
        }
    });
  });
</script>
</html>
